package me.jessyan.mvparms.demo.mvp.ui.activity;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;

import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.platform.ai.control.R;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import me.jessyan.mvparms.demo.di.component.DaggerUserComponent;
import me.jessyan.mvparms.demo.di.module.UserModule;
import me.jessyan.mvparms.demo.mvp.contract.UserContract;
import me.jessyan.mvparms.demo.mvp.model.entity.User;
import me.jessyan.mvparms.demo.mvp.presenter.UserPresenter;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class MusicActivity extends BaseActivity<UserPresenter> implements UserContract.View, View.OnClickListener, SeekBar.OnSeekBarChangeListener, ServiceConnection {
    @BindView(R.id.tv_title)
    TextView mTitle;
    @BindView(R.id.iv_back)
    View mBack;
    @BindView(R.id.playing_pre)
    ImageView playingPre;
    @BindView(R.id.playing_play)
    ImageView playingPlay;
    @BindView(R.id.playing_next)
    ImageView playingNext;
    @BindView(R.id.disc)
    ImageView disc;
    @BindView(R.id.needle)
    ImageView needle;
    @BindView(R.id.music_seek_bar)
    SeekBar mSeekBar;
    @BindView(R.id.text_switcher)
    TextSwitcher mSwitcher;
    private ObjectAnimator discAnimation,needleAnimation;//自定义指针和唱盘
    private boolean isPlaying = true;//0,1 判断是否处于播放状态
    private MediaService.MusicController mMusicController;
    private boolean running;
    //连接对象，重写OnserviceDisconnected和OnserviceConnected方法
    public ServiceConnection conn= new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mMusicController.destroy();
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

        }
    };


    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        DaggerUserComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .userModule(new UserModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(Bundle savedInstanceState) {
        //设置透明栏
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            );
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        return R.layout.activity_music; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }



    @Override
    public void initData(Bundle savedInstanceState) {
        playingPre.setOnClickListener(this);
        playingPlay.setOnClickListener(this);
        playingNext.setOnClickListener(this);
        mBack.setOnClickListener(this);
        mTitle.setText(MainActivity.MUSIC_LABEL);
        //滑动条部分
        mSeekBar.setOnSeekBarChangeListener(this);

        mSwitcher.setInAnimation(this, android.R.anim.fade_in);
        mSwitcher.setOutAnimation(this, android.R.anim.fade_out);

        Intent intent = new Intent(this, MediaService.class);
        bindService(intent, conn, BIND_AUTO_CREATE);
        setAnimations();


    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        //checkNotNull(message);
        //ArmsUtils.snackbarText(message);
        if (!message.isEmpty()) {

        }
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        mMusicController.destroy();
        finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        killMyself();
    }

    @Override
    public void setAdapter(DefaultAdapter adapter) {

    }

    @Override
    public void loginReturn(User user) {

    }

    @Override
    public void logout() {

    }

    @Override
    public void uploadResult(String string) {

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.playing_pre://前一曲
                if (discAnimation != null) {
                    discAnimation.end();
                    playing();
                }
                break;
            case R.id.playing_play://播放中
                if (isPlaying){
                    playing();
                }else {
                    if (needleAnimation != null) {
                        needleAnimation.reverse();
                        needleAnimation.end();
                        mMusicController.pause();
                    }
                    if (discAnimation != null && discAnimation.isRunning()) {
                        discAnimation.cancel();
                        mMusicController.pause();
                        float valueAvatar = (float) discAnimation.getAnimatedValue();
                        discAnimation.setFloatValues(valueAvatar, 360f + valueAvatar);
                    }
                    playingPlay.setImageResource(R.mipmap.icon_playing);
                    isPlaying = true;
                }
                break;
            case R.id.playing_next://下一曲
                if (discAnimation != null) {
                    discAnimation.end();
                    playing();
                }
                break;
            case R.id.iv_back:
                onBackPressed();
                break;
            default:
                break;
        }
    }


    //播放：1、播放音乐 2、动画旋转 3、暂停图片切换为播放按钮图片
    private void playing(){
        needleAnimation.start();
        discAnimation.start();
        playingPlay.setImageResource(R.mipmap.icon_pause);
        mMusicController.play();//播放
        isPlaying = false;
    }


    //动画设置
    private void setAnimations() {
        discAnimation = ObjectAnimator.ofFloat(disc, "rotation", 0, 360);
        discAnimation.setDuration(20000);
        discAnimation.setInterpolator(new LinearInterpolator());
        discAnimation.setRepeatCount(ValueAnimator.INFINITE);

        needleAnimation = ObjectAnimator.ofFloat(needle, "rotation", 0, 25);
        needle.setPivotX(0);
        needle.setPivotY(0);
        needleAnimation.setDuration(800);
        needleAnimation.setInterpolator(new LinearInterpolator());
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        mMusicController.setPosition(seekBar.getProgress());
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    protected void onStart() {
        super.onStart();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                running = true;
                try {
                    while (running) {
                        if (mMusicController != null) {
                            long musicDuration = mMusicController.getMusicDuration();
                            final long position = mMusicController.getPosition();
                            final Date dateTotal = new Date(musicDuration);
                            final SimpleDateFormat sb = new SimpleDateFormat("mm:ss");
                            mSeekBar.setMax((int) musicDuration);
                            mSeekBar.setProgress((int) position);
                            mSwitcher.post(
                                    new Runnable() {
                                        @Override
                                        public void run() {
                                            Date date = new Date(position);
                                            String time = sb.format(date) + "/" + sb.format(dateTotal);
                                            mSwitcher.setCurrentText(time);
                                        }
                                    }
                            );
                        }

                        Thread.sleep(500);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

    @Override
    protected void onStop() {
        running = false;
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // 解除绑定
        unbindService(this);
        super.onDestroy();
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mMusicController = ((MediaService.MusicController) service);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        mMusicController = null;
    }
}
